﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Text
Imports System.Data

Imports Yahoo.API
Imports eBay.Service.Call
Imports eBay.Service.Core.Soap
Imports eBay.Service.Core.Sdk
Imports eBay.Service.Util

Imports System
Imports System.IO
Imports Microsoft.Practices.EnterpriseLibrary.Caching
Imports com.google.api

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _ 
<WebService(Namespace:="uri:Microsoft.Practices.EnterpriseLibrary.Caching.CustomWebServiceCache")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class GigitiService
    Inherits System.Web.Services.WebService
    Implements ICustomCacheWebService

    Dim apiContext As New ApiContext

#Region "Yahoo web search"
    Protected Function RestrictGoogleLinkSize(ByVal _Link As String, ByVal _Title As String) As String
        Dim GoogleLength As Integer = CInt(ConfigurationManager.AppSettings("GoogleLength"))
        Dim _Anchar = "<a href=""{0}"" target=""_blank"" title=""{2}"" >{1}</a>"
        If _Title.Length > GoogleLength + 2 Then
            Return String.Format(_Anchar, _Link, _Title.Substring(0, GoogleLength) & "...", _Title)
        Else
            Return String.Format(_Anchar, _Link, _Title, _Title)
        End If
    End Function
    <WebMethod(EnableSession:=True)> _
    Public Function YahooWebsearch(ByVal KeyWard As String, ByVal PageIndex As Integer) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Dim _Cachedata As String() = New String(2) {}
        _Cachedata = LoadDataFromStore(String.Format("{1}@{0}$YahooWebsearch", KeyWard, PageIndex))
        If _Cachedata IsNot Nothing Then
            Return _Cachedata(0).ToString()
        End If
        Session("KeyWard") = KeyWard
        Dim Count As Integer = 4
        Dim StartIndex As Integer = (PageIndex - 1) * Count
        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.WebSearchResponse.ResultSet

        Dim _Result As New StringBuilder()
        _Result.Append("")
        resultSet = yahoo.WebSearch(YahooApiKey, KeyWard, "all", Count, StartIndex, "any", True, True, "en")
        Dim _TotalResult As Integer
        Dim i As Integer = 0
        If resultSet.Result.Length > 0 Then
            _TotalResult = CInt(CInt(resultSet.totalResultsAvailable) / Count)
            For Each result As Yahoo.API.WebSearchResponse.ResultType In resultSet.Result
                Dim _Cached As String
                If result.Cache IsNot Nothing Then
                    _Cached = result.Cache.Size.ToString & "- Cached"
                Else
                    _Cached = "0 - Cached"
                End If
                Dim _class As String
                If i Mod 2 = 1 Then
                    _class = "datagridAlterRow"
                Else
                    _class = "datagridRow"
                End If
                _Result.AppendFormat(Gigiti.Common.YahooWebsearchTemplate, RestrictGoogleLinkSize(result.Url, result.Title), result.Summary, _Cached, _class)
                i = i + 1
            Next
            _Result.Append("<div id=""YahooPanelAd"">Advertisement<div><br />")
            If PageIndex > 1 Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplate, PageIndex - 1, PageIndex + 1, PageIndex, _TotalResult, "YahooWebsearch")
            Else
                _Result.AppendFormat(Gigiti.Common.FooterTemplateStart, PageIndex + 1, PageIndex, _TotalResult, "YahooWebsearch")
            End If

        Else
            _Result.Append("no results found")
            _Result.Append("<div id=""YahooPanelAd"">Advertisement<div><br />")
        End If
        Dim vals As String() = New String(2) {}
        vals(0) = _Result.ToString().Replace(vbCrLf, "")
        vals(1) = _Result.ToString().Length.ToString()
        vals(2) = "YahooWebsearch"
        AddNewItem(String.Format("{1}@{0}$YahooWebsearch", KeyWard, PageIndex), "YahooWebsearch", vals, _Result.ToString().Length.ToString())
        Return _Result.ToString()
    End Function
#End Region

#Region "Top 10 Search For Yahoo"
    <WebMethod(EnableSession:=True)> _
    Public Function YahooWebsearchTopTen(ByVal KeyWard As String) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Session("KeyWard") = KeyWard

        Dim _Cachedata As String() = New String(2) {}
        _Cachedata = LoadDataFromStore(String.Format("{0}$YahooWebsearchTopTen", KeyWard))
        If _Cachedata IsNot Nothing Then
            Return _Cachedata(0).ToString()
        End If

        Dim Count As Integer = 10
        Dim StartIndex As Integer = 0
        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.WebSearchResponse.ResultSet
        ' 0 : RestrictGoogleLinkSize(Eval("Url"), Eval("title")), 1: snippet, 2: Cached

        Dim _Result As New StringBuilder()
        _Result.Append("")
        resultSet = yahoo.WebSearch(YahooApiKey, KeyWard, "all", Count, StartIndex, "any", True, True, "en")
        Dim _TotalResult As Integer
        Dim i As Integer = 0
        If resultSet.Result.Length > 0 Then
            _TotalResult = CInt(CInt(resultSet.totalResultsAvailable) / Count)
            For Each result As Yahoo.API.WebSearchResponse.ResultType In resultSet.Result
                Dim _Cached As String
                If result.Cache IsNot Nothing Then
                    _Cached = result.Cache.Size.ToString & "- Cached"
                Else
                    _Cached = "0 - Cached"
                End If
                Dim _class As String
                If i Mod 2 = 1 Then
                    _class = "datagridAlterRow"
                Else
                    _class = "datagridRow"
                End If
                _Result.AppendFormat(Gigiti.Common.YahooWebsearchTopTenTemplate, RestrictGoogleLinkSize(result.Url, result.Title), result.Summary, _Cached, _class)
                i = i + 1
            Next
        Else
            _Result.Append("no results found")
        End If

        Dim vals As String() = New String(2) {}
        vals(0) = _Result.ToString().Replace(vbCrLf, "")
        vals(1) = _Result.ToString().Length.ToString()
        vals(2) = "YahooWebsearchTopTen"
        AddNewItem(String.Format("{0}$YahooWebsearchTopTen", KeyWard), "YahooWebsearchTopTen", vals, _Result.ToString().Length.ToString())
        Return _Result.ToString()
    End Function
#End Region

#Region "E-Bay Web Search"
    Private Sub SetEbayCredential()
        apiContext.ApiCredential.ApiAccount.Developer = ""
        apiContext.ApiCredential.ApiAccount.Application = ""
        apiContext.ApiCredential.ApiAccount.Certificate = ""
        apiContext.ApiCredential.eBayAccount.UserName = ""
        apiContext.ApiCredential.eBayAccount.Password = ""
        apiContext.ApiCredential.eBayToken = ""
        apiContext.SoapApiServerUrl = ""
        apiContext.SignInUrl = ""
        apiContext.EPSServerUrl = ""
        apiContext.Version = ""
        apiContext.ApiLogManager = New ApiLogManager()
        apiContext.ApiLogManager.ApiLoggerList.Add(New FileLogger(Server.MapPath(ConfigurationManager.AppSettings.Get("LogFileName")), True, True, True))
        apiContext.ApiLogManager.EnableLogging = True
        apiContext.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings.Get("TimeOut").ToString)

        If Not ConfigurationManager.AppSettings.Get("EbayDevID") Is Nothing Then
            apiContext.ApiCredential.ApiAccount.Developer = ConfigurationManager.AppSettings("EbayDevID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayDevID") Is Nothing Then
            apiContext.ApiCredential.ApiAccount.Developer = ConfigurationManager.AppSettings("EbayDevID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayDevID") Is Nothing Then
            apiContext.ApiCredential.ApiAccount.Developer = ConfigurationManager.AppSettings("EbayDevID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayAppID") Is Nothing Then
            apiContext.ApiCredential.ApiAccount.Application = ConfigurationManager.AppSettings("EbayAppID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayCertID") Is Nothing Then
            apiContext.ApiCredential.ApiAccount.Certificate = ConfigurationManager.AppSettings("EbayCertID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayAuthToken") Is Nothing Then
            apiContext.ApiCredential.eBayToken = ConfigurationManager.AppSettings("EbayAuthToken").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayUserID") Is Nothing Then
            apiContext.ApiCredential.eBayAccount.UserName = ConfigurationManager.AppSettings("EbayUserID").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayUserPswd") Is Nothing Then
            apiContext.ApiCredential.eBayAccount.Password = ConfigurationManager.AppSettings("EbayUserPswd").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EbayApiServerUrl") Is Nothing Then
            apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings("EbayApiServerUrl").ToString.Replace("&amp;", "&")
        End If

        If Not ConfigurationManager.AppSettings.Get("SignInUrl") Is Nothing Then
            apiContext.SignInUrl = ConfigurationManager.AppSettings("SignInUrl").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("EpsServerUrl") Is Nothing Then
            apiContext.EPSServerUrl = ConfigurationManager.AppSettings("EpsServerUrl").ToString
        End If

        If Not ConfigurationManager.AppSettings.Get("Version") Is Nothing Then
            apiContext.Version = ConfigurationManager.AppSettings("Version").ToString
        End If

    End Sub
    Private Sub GetEbayResults(ByVal KeyWard As String)
        SetEbayCredential()
        Dim apiCall As GetSearchResultsCall = New GetSearchResultsCall(apiContext)
        apiCall.SearchFlagsList = New SearchFlagsCodeTypeCollection
        Dim findItems As SearchResultItemTypeCollection
        findItems = apiCall.GetSearchResults(KeyWard)

        If findItems.ToArray.Length > 0 Then
            Session("EbaySearchResult") = findItems
            Session("KeyWard") = KeyWard
        End If
    End Sub
    <WebMethod(EnableSession:=True)> _
   Public Function EbayWebsearch(ByVal KeyWard As String, ByVal PageIndex As Integer) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Session("KeyWard") = KeyWard
        Dim Count As Integer = 3
        Dim _Result As New StringBuilder()
        _Result.Append("")

        Dim buyItNowPrice As String = ""
        Dim bestOfferPrice As String = ""
        Dim TimeLeft As String = ""
        Dim _TotalResult As Integer
        Dim findItems As SearchResultItemTypeCollection
        If Session("KeyWard") IsNot Nothing Then
            GetEbayResults(KeyWard)
        ElseIf Session("EbaySearchResult") IsNot Nothing And Session("KeyWard") = KeyWard Then
            findItems = DirectCast(Session("EbaySearchResult"), SearchResultItemTypeCollection)
            If findItems.ToArray.Length = 0 Then
                GetEbayResults(KeyWard)
            End If
        Else
            GetEbayResults(KeyWard)
        End If
        findItems = DirectCast(Session("EbaySearchResult"), SearchResultItemTypeCollection)
        _TotalResult = CInt(findItems.ToArray.Length / Count)
        If _TotalResult > 0 Then
            Dim j As Integer = 0
            Dim i As Integer = 0
            For i = (Count * (PageIndex - 1) + 1) To (Count * PageIndex)
                If Not findItems(i).Item.BuyItNowPrice Is Nothing Then
                    buyItNowPrice = CurrencyUtility.GetCurrencySymbol(findItems(i).Item.BuyItNowPrice.currencyID) & " " & FormatNumber(findItems(i).Item.BuyItNowPrice.Value.ToString, -1)
                Else
                    buyItNowPrice = "-"
                End If
                Dim _class As String
                If j Mod 2 = 1 Then
                    _class = "datagridAlterRow"
                Else
                    _class = "datagridRow"
                End If
                _Result.AppendFormat(Gigiti.Common.EbayWebsearchTemplate, findItems(i).Item.ListingDetails.ViewItemURLForNaturalSearch, findItems(i).Item.PictureDetails.GalleryURL, findItems(i).Item.Title, findItems(i).Item.SellingStatus.BidCount, CurrencyUtility.GetCurrencySymbol(findItems(i).Item.SellingStatus.CurrentPrice.currencyID) & FormatNumber(findItems(i).Item.SellingStatus.CurrentPrice.Value.ToString, -1), buyItNowPrice, findItems(i).Item.ListingDetails.EndTime, _class)
                j = j + 1
            Next

            _Result.Append("<div id=""EbayPanelAd"">Advertisement<div><br />")
            If PageIndex = 1 Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplateStart, PageIndex + 1, PageIndex, _TotalResult, "EbayWebsearch")
            ElseIf PageIndex = _TotalResult Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplateEnd, PageIndex - 1, PageIndex, _TotalResult, "EbayWebsearch")
            Else
                _Result.AppendFormat(Gigiti.Common.FooterTemplate, PageIndex - 1, PageIndex + 1, PageIndex, _TotalResult, "EbayWebsearch")
            End If

        Else
            _Result.Append("no results found")
            _Result.Append("<div id=""EbayPanelAd"">Advertisement<div><br />")
        End If

        Return _Result.ToString()
    End Function
#End Region

#Region "Top 10 Rank"
    Protected Function CreateCommentsLink(ByVal _Text As String, ByVal _Link As String) As String
        Dim _Anchar = "<a href=""{0}"" target=""_blank"" style=""color:#0000FF;"" title=""{0}"" >{1}</a>"
        If Not _Link.StartsWith("http") Then
            _Link = String.Format("http://{0}", _Link)
        End If
        Return String.Format(_Anchar, _Link, _Text)
    End Function
    Protected Function RestrictLinkSize(ByVal _Link As String) As String
        Dim _Anchar = "<div title=""{0}"" >{1}</div>"
        If _Link.Length > 30 Then
            Return String.Format(_Anchar, _Link, _Link.Substring(0, 28) & "...")
        Else
            Return String.Format(_Anchar, _Link, _Link)
        End If
    End Function
    Protected Function CreateAddCommentsLink(ByVal Website_Name As String) As String
        Dim _Anchar = "<img title=""Read and Rate"" alt=""Read and Rate"" onclick=""AddComments('{0}');"" src=""{1}"" style=""cursor:pointer;""/>"
        'TopTen.aspx?Edit={0}
        Return String.Format(_Anchar, Website_Name, Gigiti.Common.ResolveUrl("~/images/Read.gif"))
    End Function
    Protected Function StarRating(ByVal Rate As Integer) As String
        Dim _StarText As String = "<img src=""{0}"" title=""{1}"" alt=""{1}"" style=""float: left;"">"
        Dim _ResultString = New StringBuilder
        Dim i As Integer = 0
        For i = 1 To Rate
            _ResultString.AppendFormat(_StarText, Gigiti.Common.ResolveUrl("~/App_Themes/myTheme/images/FilledStar.png"), i)
        Next
        For i = (Rate + 1) To 10
            _ResultString.AppendFormat(_StarText, Gigiti.Common.ResolveUrl("~/App_Themes/myTheme/images/EmptyStar.png"), i)
        Next
        Return _ResultString.ToString()
    End Function
    <WebMethod(EnableSession:=True)> _
    Public Function TopTenRank(ByVal SubCategory As String) As String
        'Dim _Cachedata As String() = New String(2) {}
        '_Cachedata = LoadDataFromStore(String.Format("{0}$TopTenRank", SubCategory))
        'If _Cachedata IsNot Nothing Then
        '    Return _Cachedata(0).ToString()
        'End If

        Dim _Suggestion As New BusinessLogic.Suggestion()
        _Suggestion.SubCategory = SubCategory
        Dim _Result As New StringBuilder()

        Dim dt As DataTable = _Suggestion.Load()
        Dim i As Integer = 0
        Dim dr As DataRow
        For Each dr In dt.Rows
            Dim _class As String
            If i Mod 2 = 1 Then
                _class = "datagridAlterRow"
            Else
                _class = "datagridRow"
            End If
            _Result.AppendFormat(Gigiti.Common.TopTenRankTemplate, CreateCommentsLink(dr("Website_Name"), dr("Link")), StarRating(CInt(dr("rating"))), RestrictLinkSize(dr("Link").ToString()), CreateAddCommentsLink(dr("Website_Name").ToString()), _class)
            i = i + 1
        Next
        'Dim vals As String() = New String(2) {}
        'vals(0) = _Result.ToString().Replace(vbCrLf, "")
        'vals(1) = _Result.ToString().Length.ToString()
        'vals(2) = "TopTenRank"
        'AddNewItem(String.Format("{0}$TopTenRank", SubCategory), "TopTenRank", vals, _Result.ToString().Length.ToString())

        Return _Result.ToString()
    End Function
#End Region

#Region "View Comments"
    Protected Function FixCommentLength(ByVal _Comments As String) As String
        Dim CommentsLength As Integer = CInt(ConfigurationManager.AppSettings("CommentsLength"))
        If _Comments.Length > CommentsLength + 2 Then
            Return _Comments.Substring(0, CommentsLength) & "..."
        Else
            Return _Comments
        End If
    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function ViewComments(ByVal WebsiteName As String) As String
        Dim _Rating As New BusinessLogic.Rating
        _Rating.Website_Name = WebsiteName

        Dim _Result As New StringBuilder()

        Dim dt As DataTable = _Rating.LoadBySite()
        Dim i As Integer = 0
        Dim dr As DataRow
        For Each dr In dt.Rows
            Dim _class As String
            If i Mod 2 = 1 Then
                _class = "datagridAlterRow"
            Else
                _class = "datagridRow"
            End If
            _Result.AppendFormat(Gigiti.Common.ViewCommentsTemplate, StarRating(CInt(dr("rating"))), dr("DatetimeStamp"), dr("Comments"), FixCommentLength(dr("Comments").ToString()), dr("Username"), _class)
            i = i + 1
        Next
        Return _Result.ToString()
    End Function
#End Region

#Region "Add Comments"
    <WebMethod(EnableSession:=True)> _
    Public Function AddComments(ByVal WebsiteName As String, ByVal Yourrating As Integer, ByVal YourComments As String) As String
        If Session("Username") IsNot Nothing Then
            Dim _Rating As New BusinessLogic.Rating
            _Rating.Website_Name = WebsiteName
            _Rating.Username = Session("Username").ToString()
            _Rating.Rating = Yourrating
            _Rating.Comments = YourComments
            _Rating.IPAddress = HttpContext.Current.Request.UserHostAddress

            _Rating.Save()
            Return "Thank you for your comments."
        End If
        Return "Please Login to post a comments."
    End Function
#End Region

#Region "Yahoo Image Search"
    <WebMethod(EnableSession:=True)> _
    Public Function YahooImageSearch(ByVal KeyWard As String, ByVal PageIndex As Integer) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Session("KeyWard") = KeyWard
        Dim _Cachedata As String() = New String(2) {}
        Dim safeSearch As Boolean
        If Session("SafeSearch") Is Nothing Then
            safeSearch = False
        Else
            safeSearch = True
        End If
        _Cachedata = LoadDataFromStore(String.Format("{1}@{0}{2}$YahooImageSearch", KeyWard, PageIndex, safeSearch))
        If _Cachedata IsNot Nothing Then
            Return _Cachedata(0).ToString()
        End If

        Dim Count As Integer = 10
        Dim StartIndex As Integer = (PageIndex - 1) * Count
        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.ImageSearchResponse.ResultSet

        Dim _Result As New StringBuilder()
        _Result.Append("<table width=""100%"" border=""0"" cellpadding=""0"" cellspacing=""0""><tr>")



        resultSet = yahoo.ImageSearch(YahooApiKey, KeyWard, "all", Count, PageIndex, "any", safeSearch)
        Dim _TotalResult As Integer
        If resultSet.Result.Length > 0 Then
            _TotalResult = CInt(CInt(resultSet.totalResultsAvailable) / Count)
            Dim i As Integer = 0
            For Each result As Yahoo.API.ImageSearchResponse.ResultType In resultSet.Result
                Dim Summary As String

                Dim _temp = result.RefererUrl.Split("/")
                If result.Summary.Length > 20 Then
                    Summary = result.Summary.Substring(0, 17) & "..."
                Else
                    Summary = result.Summary
                End If

                Dim _class As String = "ImageSearchResult"
                If i Mod 5 = 0 Then
                    _Result.Append("</tr><tr>")
                End If
                _Result.Append("<td align=""center"">")
                _Result.AppendFormat(Gigiti.Common.YahooImageSearchTemplate, result.Url, result.Thumbnail.Url, Summary, result.Width, result.Height, result.FileSize, result.FileFormat, _temp(2), _class)
                _Result.Append("</td>")
                i = i + 1
            Next
            _Result.Append("</tr><tr><td align=""center"" colspan=""5"">")
            If PageIndex > 1 Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplate, PageIndex - 1, PageIndex + 1, PageIndex, _TotalResult, "YahooImageSearch")
            Else
                _Result.AppendFormat(Gigiti.Common.FooterTemplateStart, PageIndex + 1, PageIndex, _TotalResult, "YahooImageSearch")
            End If
            _Result.Append("</td></tr></table>")
        Else
            _Result.Append("no results found")
        End If
        Dim vals As String() = New String(2) {}
        vals(0) = _Result.ToString().Replace(vbCrLf, "")
        vals(1) = _Result.ToString().Length.ToString()
        vals(2) = "YahooImageSearch"
        AddNewItem(String.Format("{1}@{0}{2}$YahooImageSearch", KeyWard, PageIndex, safeSearch), "YahooImageSearch", vals, _Result.ToString().Length.ToString())
        Return _Result.ToString()
    End Function
#End Region

#Region "Yahoo Video Search"
    <WebMethod(EnableSession:=True)> _
    Public Function YahooVideoSearch(ByVal KeyWard As String, ByVal PageIndex As Integer) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Session("KeyWard") = KeyWard
        Dim _Cachedata As String() = New String(2) {}
        Dim safeSearch As Boolean
        If Session("SafeSearch") Is Nothing Then
            safeSearch = False
        Else
            safeSearch = True
        End If
        _Cachedata = LoadDataFromStore(String.Format("{1}@{0}{2}$YahooVideoSearch", KeyWard, PageIndex, safeSearch))
        If _Cachedata IsNot Nothing Then
            Return _Cachedata(0).ToString()
        End If

        Dim Count As Integer = 10
        Dim StartIndex As Integer = (PageIndex - 1) * Count
        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.VideoSearchResponse.ResultSet

        Dim _Result As New StringBuilder()
        _Result.Append("<table width=""100%"" border=""0"" cellpadding=""0"" cellspacing=""0""><tr>")


        resultSet = yahoo.VideoSearch(YahooApiKey, KeyWard, "all", Count, PageIndex, "any", safeSearch)

        Dim _TotalResult As Integer
        If resultSet.Result.Length > 0 Then
            _TotalResult = CInt(CInt(resultSet.totalResultsAvailable) / Count)
            Dim i As Integer = 0
            For Each result As Yahoo.API.VideoSearchResponse.ResultType In resultSet.Result
                Dim DescriptionText As String
                If result.Title.Length > 20 Then
                    DescriptionText = result.Title.Substring(0, 17) & "..."
                Else
                    DescriptionText = result.Title
                End If

                Dim _class As String = "VideoSearchResult"
                If i Mod 5 = 0 Then
                    _Result.Append("</tr><tr>")
                End If
                _Result.Append("<td align=""center"">")
                _Result.AppendFormat(Gigiti.Common.YahooVideoSearchTemplate, result.Url, result.Thumbnail.Url, result.Title, DescriptionText, _class)
                _Result.Append("</td>")
                i = i + 1
            Next

            _Result.Append("</tr><tr><td align=""center"" colspan=""5"">")
            If PageIndex > 1 Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplate, PageIndex - 1, PageIndex + 1, PageIndex, _TotalResult, "YahooVideoSearch")
            Else
                _Result.AppendFormat(Gigiti.Common.FooterTemplateStart, PageIndex + 1, PageIndex, _TotalResult, "YahooVideoSearch")
            End If
            _Result.Append("</td></tr></table>")
        Else
            _Result.Append("no results found")
        End If
        Dim vals As String() = New String(2) {}
        vals(0) = _Result.ToString().Replace(vbCrLf, "")
        vals(1) = _Result.ToString().Length.ToString()
        vals(2) = "YahooVideoSearch"
        AddNewItem(String.Format("{1}@{0}{2}$YahooVideoSearch", KeyWard, PageIndex, safeSearch), "YahooVideoSearch", vals, _Result.ToString().Length.ToString())
        Return _Result.ToString()
    End Function
#End Region

#Region "Yahoo News Search"
    Protected Function CreateNewsImage(ByVal _Image As String, ByVal _Summary As String) As String
        Dim _RetVal As String = ""
        If _Image.Length > 0 Then
            _RetVal = [String].Format("<img src=""{0}"" title=""{1}"" alt=""Summary""/>", _Image, _Summary)
        End If
        Return _RetVal
    End Function

    <WebMethod(EnableSession:=True)> _
    Public Function YahooNewsSearch(ByVal KeyWard As String, ByVal PageIndex As Integer) As String
        KeyWard = KeyWard.Replace("""", "").Replace("'", "").Replace("/", "").Replace("\", "")
        Session("KeyWard") = KeyWard
        Dim _Cachedata As String() = New String(2) {}
        _Cachedata = LoadDataFromStore(String.Format("{1}@{0}$YahooNewsSearch", KeyWard, PageIndex))
        If _Cachedata IsNot Nothing Then
            Return _Cachedata(0).ToString()
        End If

        Dim Count As Integer = 10
        Dim StartIndex As Integer = (PageIndex - 1) * Count
        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.NewsSearchResponse.ResultSet

        Dim _Result As New StringBuilder()
        _Result.Append("<table width=""100%"" border=""0"" cellpadding=""0"" cellspacing=""5"">")
        Dim safeSearch As Boolean
        If Session("SafeSearch") Is Nothing Then
            safeSearch = True
        Else
            safeSearch = False
        End If


        resultSet = yahoo.NewsSearch(YahooApiKey, KeyWard, "all", Count, PageIndex, "rank", "en")
        Dim _TotalResult As Integer
        Dim i As Integer = 0
        If resultSet.Result.Length > 0 Then
            _TotalResult = CInt(CInt(resultSet.totalResultsAvailable) / Count)
            For Each result As Yahoo.API.NewsSearchResponse.ResultType In resultSet.Result
                Dim Thumbnail As String
                If result.Thumbnail IsNot Nothing Then
                    Thumbnail = result.Thumbnail.Url
                Else
                    Thumbnail = ""
                End If

                Dim _class As String
                _class = "NewsSearchResult"
                _Result.Append("<tr><td>")
                _Result.AppendFormat(Gigiti.Common.YahooNewsSearchTemplate, CreateNewsImage(Thumbnail, result.Summary), result.Url, result.Title, result.Summary, result.PublishDate, _class)
                _Result.Append("</td></tr>")
                i = i + 1
            Next
            _Result.Append("</table>")
            If PageIndex > 1 Then
                _Result.AppendFormat(Gigiti.Common.FooterTemplate, PageIndex - 1, PageIndex + 1, PageIndex, _TotalResult, "YahooNewsSearch")
            Else
                _Result.AppendFormat(Gigiti.Common.FooterTemplateStart, PageIndex + 1, PageIndex, _TotalResult, "YahooNewsSearch")
            End If

        Else
            _Result.Append("no results found")
        End If
        Dim vals As String() = New String(2) {}
        vals(0) = _Result.ToString().Replace(vbCrLf, "")
        vals(1) = _Result.ToString().Length.ToString()
        vals(2) = "YahooNewsSearch"
        AddNewItem(String.Format("{1}@{0}{2}$YahooNewsSearch", KeyWard, PageIndex, safeSearch), "YahooNewsSearch", vals, _Result.ToString().Length.ToString())
        Return _Result.ToString()
    End Function
#End Region

#Region "Recent News"
    <WebMethod(EnableSession:=True)> _
    Public Function YahooRecrntNews() As String

        Dim Count As Integer = 8

        Dim YahooApiKey As String = ConfigurationManager.AppSettings("YahooAPIKey").ToString
        Dim yahoo As New YahooSearchService
        Dim resultSet As Yahoo.API.NewsSearchResponse.ResultSet

        Dim _Result As New StringBuilder()
        _Result.Append("")

        resultSet = yahoo.NewsSearch(YahooApiKey, ConfigurationManager.AppSettings("RecentNews"), "all", Count, 1, "rank", "en")
        If resultSet.Result.Length > 0 Then
            For Each result As Yahoo.API.NewsSearchResponse.ResultType In resultSet.Result
                Dim Title As String

                If result.Title.Length > 70 Then
                    Title = result.Title.Substring(0, 67) & "..."
                Else
                    Title = result.Title
                End If

                _Result.AppendFormat(Gigiti.Common.YahooRecentNewsTemplate, result.Url, result.Summary, Title)
            Next
        End If
        Return _Result.ToString()
    End Function
#End Region

#Region "Cache Methode"
    <WebMethod(Description:="Returns the number of items in the specified cache partition.")> _
 Public Function CachedItemCount(ByVal partitionName As String) As Int32 _
   Implements ICustomCacheWebService.CachedItemCount
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Directory.Exists(filePath) Then
            ' create file specification to search for cache files
            Dim searchString As String = String.Concat("*", Gigiti.Common.DataExtension)
            Try
                Dim cacheFiles() As String = Directory.GetFiles(filePath, searchString, SearchOption.TopDirectoryOnly)
                Return cacheFiles.Length
            Catch
                Return -1  ' error indicator
            End Try
        Else
            Return 0     ' partition folder does not exist, so no cached items
        End If
    End Function
    <WebMethod(Description:="Adds a new item to the specified cache partition.")> _
    Public Function AddNewItem(ByVal partitionName As String, ByVal storageKey As String, _
            ByVal cachedItemInfo() As String, ByVal base64ItemBytes As String) As String _
      Implements ICustomCacheWebService.AddNewItem
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Not Directory.Exists(filePath) Then
            Try
                Directory.CreateDirectory(filePath)
            Catch ex As Exception
                Return "Cannot create partition folder '" & filePath & "'. " & ex.Message
            End Try
        End If
        ' create path and file names for information and data files
        Dim infoFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.InfoExtension))
        Dim dataFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.DataExtension))
        Try
            ' create information file
            If File.Exists(infoFile) Then
                File.Delete(infoFile)
            End If
            File.WriteAllLines(infoFile, cachedItemInfo)
        Catch ex As Exception
            Return "Cannot create information file '" & infoFile & "'. " & ex.Message
        End Try
        ' decode object from Base64 string and write to data file
        Dim itemBytes() As Byte = Convert.FromBase64String(base64ItemBytes)
        Try
            ' create data file
            If File.Exists(dataFile) Then
                File.Delete(dataFile)
            End If
            File.WriteAllBytes(dataFile, itemBytes)
            Return String.Empty
        Catch ex As Exception
            Return "Cannot create data file '" & dataFile & "'. " & ex.Message
        End Try
    End Function
    <WebMethod(Description:="Removes the specified item from the specified cache partition.")> _
    Public Function Remove(ByVal partitionName As String, ByVal storageKey As String) As String _
      Implements ICustomCacheWebService.Remove
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Not Directory.Exists(filePath) Then
            Return "Specified cache partition '" & partitionName & "' does not exist"
        End If
        ' create path and file names for information and data files
        Dim dataFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.DataExtension))
        Dim infoFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.InfoExtension))
        If File.Exists(dataFile) Then
            Try
                ' delete data and information files
                File.Delete(dataFile)
                File.Delete(infoFile)
                Return String.Empty
            Catch ex As Exception
                Return "Error while removing cached item. " & ex.Message
            End Try
        Else
            Return "The specified item does not exist in the cache partition '" & partitionName & "'"
        End If
    End Function
    <WebMethod(Description:="Removes any existing item from the cache with the same key as a new item.")> _
    Public Function RemoveOldItem(ByVal partitionName As String, ByVal storageKey As String) As String _
      Implements ICustomCacheWebService.RemoveOldItem
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Directory.Exists(filePath) Then
            ' create path and file names for information and data files
            Dim dataFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.DataExtension))
            Dim infoFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.InfoExtension))
            Try
                ' delete data file
                File.Delete(dataFile)
            Catch
            End Try
            Try
                ' delete information file
                File.Delete(infoFile)
            Catch
            End Try
        End If
        Return String.Empty
    End Function
    <WebMethod(Description:="Updates the last accessed time for the specified item in the specified cache partition.")> _
    Public Function UpdateLastAccessedTime(ByVal partitionName As String, ByVal _
                    storageKey As String, ByVal timestamp As DateTime) As String _
      Implements ICustomCacheWebService.UpdateLastAccessedTime
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Not Directory.Exists(filePath) Then
            Return "Specified cache partition '" & partitionName & "' does not exist"
        End If
        ' create path and file name for information file
        Dim infoFile As String = Path.Combine(filePath, String.Concat(storageKey.ToString(), Gigiti.Common.InfoExtension))
        If File.Exists(infoFile) Then
            Try
                ' get existing information array and update it
                Dim infoData() As String = File.ReadAllLines(infoFile)
                infoData(1) = timestamp.ToString()
                File.Delete(infoFile)
                File.WriteAllLines(infoFile, infoData)
                Return String.Empty
            Catch ex As Exception
                Return "Error while updating cache info file '" & infoFile & "'. " & ex.Message
            End Try
        Else
            Return "Cache information file '" & infoFile & "' does not exist"
        End If
    End Function
    <WebMethod(Description:="Removes all cached items from the specified cache partition.")> _
    Public Function Flush(ByVal partitionName As String) As String _
      Implements ICustomCacheWebService.Flush
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Not Directory.Exists(filePath) Then
            Return "Specified cache partition '" & partitionName & "' does not exist"
        End If
        ' create file specification to search for cache files
        Dim searchString As String = String.Concat("*", Gigiti.Common.DataExtension)
        Dim cacheFiles() As String = Directory.GetFiles(filePath, searchString, SearchOption.TopDirectoryOnly)
        For Each cacheFile As String In cacheFiles
            ' create path and file names for information and data files
            Dim dataFile As String = Path.Combine(filePath, cacheFile)
            Dim infoName As String = String.Concat(Path.GetFileNameWithoutExtension(cacheFile), Gigiti.Common.InfoExtension)
            Dim infoFile As String = Path.Combine(filePath, infoName)
            Try
                ' delete this data file
                File.Delete(dataFile)
            Catch ex As Exception
                Return "Error while deleting cache data file '" & dataFile & "'. " & ex.Message
            End Try
            Try
                ' delete this information file
                File.Delete(infoFile)
            Catch ex As Exception
                Return "Error while deleting cache information file '" & infoFile & "'. " & ex.Message
            End Try
        Next
        Return String.Empty
    End Function
    <WebMethod(Description:="Returns a String array containing all the cached items for the specified partition.")> _
    Public Function LoadDataFromStore(ByVal partitionName As String) As String() _
      Implements ICustomCacheWebService.LoadDataFromStore
        ' create String array to hold error message
        Dim errorMessage(0) As String
        ' create partition folder path and check if it exists
        Dim filePath As String = Path.Combine(Gigiti.Common.CacheRootFilePath, partitionName)
        If Not Directory.Exists(filePath) Then
            ' this method is called when the Caching App Block first
            ' accesses the cache, and so the code must create the directory
            ' for the specified partition to allow the block to work with it
            Try
                Directory.CreateDirectory(filePath)
            Catch ex As Exception
                errorMessage(0) = "Cannot create partition folder '" & filePath & "'. " & ex.Message
                Return errorMessage
            End Try
        End If
        ' create file specification to search for cache files
        Dim searchString As String = String.Concat("*", Gigiti.Common.DataExtension)
        Dim cacheFiles() As String
        Try
            ' get a list of cache data files
            cacheFiles = Directory.GetFiles(filePath, searchString, SearchOption.TopDirectoryOnly)
        Catch ex As Exception
            errorMessage(0) = "Cannot access cache in partition '" & partitionName & "'." & ex.Message
            Return errorMessage
        End Try
        If cacheFiles.Length > 0 Then
            Try
                ' create String array to contain cached item information and data
                ' array contains four entries for each cache item and repeats in multiples of 4:
                ' - Index &0 = cache key
                ' - Index &1 = last accessed date/time
                ' - Index &2 = duration (seconds)
                ' - Index &3 = Base64 encoded data
                Dim cachedItems((cacheFiles.Length * 4) - 1) As String
                Dim itemIndex As Int32 = 0
                ' iterate through cached files adding data to String array
                For Each cacheFile As String In cacheFiles
                    ' create path and file name for information file
                    Dim infoName As String = String.Concat(Path.GetFileNameWithoutExtension(cacheFile), Gigiti.Common.InfoExtension)
                    Dim infoPath As String = Path.Combine(filePath, infoName)
                    ' read from information file
                    ' does not support callbacks or priorities - uses standard values
                    Dim infoData() As String = File.ReadAllLines(infoPath)
                    cachedItems(itemIndex) = infoData(0)
                    cachedItems(itemIndex + 1) = infoData(1)
                    cachedItems(itemIndex + 2) = infoData(2)
                    ' base64-encode object from .cachefile file
                    Dim itemBytes() As Byte = File.ReadAllBytes(Path.Combine(filePath, cacheFile))
                    cachedItems(itemIndex + 3) = Convert.ToBase64String(itemBytes)
                    itemIndex += 4
                Next
                Return cachedItems
            Catch ex As Exception
                errorMessage(0) = "Error reading cached items from partition '" & partitionName & "'. " & ex.Message
                Return errorMessage
            End Try
        Else
            Return Nothing   ' no cached items
        End If
    End Function
#End Region

#Region "Spell Word"
    <WebMethod(EnableSession:=True)> _
    Public Function Spellword(ByVal Word As String) As String
        Dim _RetVal As String = ""
        Dim _ResultTemplate As String = "Did you mean: <a href=""javascript:void(0);"" onclick=""SearchSpellword('{0}');"">{0}</a>"
        If Word.Length > 0 Then
            Dim GoogleAPIKey As String = ConfigurationManager.AppSettings("GoogleAPIKey").ToString
            Dim GoogleWebSearchService As New GoogleSearchService
            Dim _GoogleWords = GoogleWebSearchService.doSpellingSuggestion(GoogleAPIKey, Word)
            Dim IsIdentical = String.Compare(Word, _GoogleWords)
            If IsIdentical Then
                If _GoogleWords IsNot Nothing Then
                    _RetVal = String.Format(_ResultTemplate, _GoogleWords.Replace("'", ""))
                Else
                    _RetVal = "Spelling is Correct"
                End If
            End If
        End If
        Return _RetVal
    End Function
#End Region

#Region "Safe Search"
    <WebMethod(EnableSession:=True)> _
    Public Function SafeSearch(ByVal IsSafe As Boolean) As String
        If IsSafe Then
            Session("SafeSearch") = Nothing
            Return "SafeSearch is <a href=""javascript:void(0);"" onclick=""SafeSearch(true);"">On</a>"
        Else
            Session("SafeSearch") = IsSafe
            Return "SafeSearch is <a href=""javascript:void(0);"" onclick=""SafeSearch(false);"">Off</a>"
        End If
    End Function
#End Region

End Class
